package com.geek.jdbc.work1.dao;

/*
 *@Date 2025/11/17
 *@Author wangpeng
 *@Description TODO
 */


import com.geek.jdbc.work1.entity.Admin;
import com.geek.jdbc.work1.utils.JDBCUtils;

import java.sql.*;

public class AdminDao {

    public Admin findByUsernameAndPassword(String username, String password) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Admin admin = null;

        try {
            // 获取连接
            conn = JDBCUtils.getConn();

            // 编写SQL
            String sql = "SELECT * FROM admin WHERE username = ? AND password = ?";

            // 预编译SQL
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);

            // 执行查询
            rs = pstmt.executeQuery();

            // 处理结果集
            if (rs.next()) {
                int id = rs.getInt("id");
                String dbUsername = rs.getString("username");
                String dbPassword = rs.getString("password");
                admin = new Admin(id, dbUsername, dbPassword);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            JDBCUtils.close(pstmt, conn, rs);
        }

        return admin;
    }

}
